<template>
    <div class="app-container">           
        <avue-form :option="pluginColumn" v-model="pluginForm" @submit="handlePlugin">     
            <template v-for="column in slotColumns" :slot="column.slot">
                <el-col :key="column.solt">
                    <el-form-item v-for="item in column.option.column" 
                    :key="item.label"
                    :label="item.label"
                    size="small">
                        <el-input :value="item.label"></el-input>
                    </el-form-item>
                </el-col>
            </template>
        </avue-form>
    </div>
</template>
<script>
import {pluginSchemaByName,kongPluginAdd,kongPluginUpdate} from '@/api/kong/plugins'
export default {
    props:{
        pluginName:{
            type:String,
            default: ""
        },
        plugin:{
            type:Object,
            required: true,
            config:{},
        },
        operate:{
            type: String,
            default:"add",
        },
        service:{
            type: Object,
            default: null
        },
        route:{
            type: Object,
            default: null
        },
        consumer:{
            type: Object,
            default: null
        },       
    },
    data(){
        return{
            // plugin 参数
            fields:[],
            // 表单提交
            form:{},
            pluginColumn: {
                label:"新增插件:"+ this.pluginName,
                labelPosition: 'top',
                // card: true,
                column: [],
                },
            slotColumns: [],
            tagsColumn: [],
            pluginForm: {enabled: true},
            pluginEntity: _.cloneDeep(this.plugin),
        }
    },
    created(){   
        // console.log(JSON.stringify(this.plugin));
        console.log(JSON.stringify(this.pluginEntity));
        this.pluginForm = this.pluginEntity["config"] || {};
        
        this.getPluginSchemaByName(); 
        
    },
    methods:{
        getPluginSchemaByName(){
            // 获取插件信息
            pluginSchemaByName(this.pluginName).then(res =>{
                // 返回数据处理
                if(!res.data){
                    return;
                }
                this.fields=res.data.fields;
                // console.log(this.fields)
                this.fields.forEach((item)=>{
                    for(let v in item){
                        let _column = this.createColumn(v, item[v]);
                        this.pluginColumn.column.push(_column);
                    }
                });
                if(this.slotColumns.length>0){
                    let _pluginColumns = {group: [], card: true};
                    let _defaultGroup = {label: "基本信息", column: []};
                    let _slotGroups = [];
                    this.pluginColumn.column.forEach((_column)=>{
                        let _exits = false;
                        this.slotColumns.forEach((_slotColumn) =>{
                            if(_slotColumn.slot == _column.prop){
                                _exits = true;
                                let _pluginColumns =[];
                                _slotColumn.option.column.forEach((_itemColumn)=>{
                                    _itemColumn.prop =_slotColumn.slot +"_" +_itemColumn.prop;
                                    _itemColumn["type"] == "array" && this.createTagColumn(_itemColumn.prop);
                                    _pluginColumns.push(_itemColumn);
                                    let _childRealProp = _itemColumn.prop.replace(_slotColumn.slot + "_","");

                                    // console.log( "_slotColumn:"+JSON.stringify(_slotColumn));
                                    // console.log( "_itemColumn:"+JSON.stringify(_itemColumn));
                                    // console.log("pluginEntity:"+JSON.stringify(this.pluginEntity));
                                    // console.log("_childRealProp:"+JSON.stringify(_childRealProp));
                                    if (this.pluginEntity.config[_slotColumn.slot]) {
                                        this.pluginForm[_itemColumn.prop] = this.pluginEntity.config[_slotColumn.slot][_childRealProp];
                                    } else {
                                        if (_itemColumn["type"] == "array") {
                                            this.pluginForm[_itemColumn.prop] = [];
                                        } else {
                                            this.pluginForm[_itemColumn.prop] = _itemColumn.value;
                                        }
                                    }
                                    
                                   

                                });
                                _slotGroups.push({
                                    label: _slotColumn.slot,
                                    column: _pluginColumns,
                                })
                            }
                        });
                        if(!_exits){
                            _defaultGroup.column.push(_column);
                        }
                    });
                    
                    _pluginColumns.group.push(_defaultGroup);
                    _pluginColumns.group.push(..._slotGroups);
                    this.pluginColumn=_pluginColumns;
                }

                // console.log("pluginColumn:"+JSON.stringify(this.pluginColumn))
            })
        },

        createColumn(label,item,child){
            let _column = {
                label: label,
                span: 24,
                prop: label,
                labelWidth: 220,
                rules: [],
                value: null,
            };
            _column.value=item.default;
            let _fields = item.fields;
            if(_fields){
                // console.log("_fields:"+JSON.stringify(_fields))
                _column.formslot = true;
                let children = {option: {column: []}, slot: ""};
                children.slot = label;
                children.form = {};
                _fields.forEach((item) => {
                    for (var v in item) {
                        children.option.column.push(this.createColumn(v, item[v], true));
                    }
                });
                this.slotColumns.push(children);
            }
            else if (item["type"] == "array" || item["type"] == "set"){
                _column.type = "array";
                _column.formslot = true;
                if (item['elements'] && item['elements']["one_of"]){
                    _column.type = "checkbox";
                    _column.formslot = false;

                    let _dics=[];
                    item['elements']["one_of"].forEach((label) => {
                        _dics.push({label: label, value: label});
                    });
                    _column.dicData = _dics;
                }
                this.createTagColumn(label);
            }else{
                let _type = item["type"];
                if (_type && _type.trim() != "") {
                    _type = this.getColumnType(_type);
                }

                //设置为必填项
                if (item["required"]) {
                    _column["rules"].push({
                        required: item["required"],
                        message: "请填写" + label,
                        trigger: "blur",
                    });
                }

                //获取默认值
                if (item["default"] && !!!child) {
                    this.pluginForm[label] = item["default"];
                }
                _column.type = _type;

                //为下拉表时，设置dicData;
                if (item["one_of"]) {
                    _column.type = "select";

                    let _dics = [];
                    item["one_of"].forEach((label) => {
                        _dics.push({label: label, value: label});
                    });
                    _column.dicData = _dics;
                }
            }
            return _column;
        },

        createTagColumn(label) {
            let tagItem = {};
            tagItem.slot = label;
            tagItem.tags = [];
            tagItem.column = label;
            tagItem.name = label;
            this.tagsColumn.push(tagItem);
        },

        getColumnType(type){            
            switch (type) {
                case "string":
                    return "input";
                case "boolean":
                    return "switch";
                case "integer":
                    return "number";
                case "number":
                    return "number";
                case "set":
                case "array":
                    return "Array";
            }
            return "";
        },

        handlePlugin(row,done){
            let _config ={};            
            for (var p in this.pluginForm) {
                    let _value = this.pluginForm[p];
                    if (p.indexOf("$") == -1 && p != "enabled" && _value != "") {
                        _config[p] = _value;
                    }
            }
            this.pluginForm = _config;
            this.pluginEntity.config = Object.assign(this.pluginForm, this.config);

            console.log("slotColumns:"+JSON.stringify(this.slotColumns));

            this.slotColumns.forEach((parentColumn)=>{
                let _column = parentColumn.slot;
                parentColumn.option.column.forEach((childColumn)=>{
                    let _columnConfig = this.pluginEntity.config[childColumn.prop];
                    if (_columnConfig === "" || _columnConfig) {
                        delete this.pluginEntity.config[childColumn.prop];
                        let _parentConfig =
                            this.pluginEntity.config[parentColumn.slot] || {};
                        let childRealProp = childColumn.prop.replace(
                            parentColumn.slot + "_",
                            ""
                        );

                        _parentConfig[childRealProp] =
                            _columnConfig === "" ? null : _columnConfig;
                        this.pluginEntity.config[parentColumn.slot] = _parentConfig;
                    }
                })
            });

            // 新增插件
            console.log("pluginEntity:"+JSON.stringify(this.pluginEntity));

            if(this.operate=="add"){
                this.pluginEntity["enabled"] = true;
                kongPluginAdd(this.pluginEntity).then(res=>{
                    this.msgSuccess("新增成功");
                    this.handleCallback();
                    // console.log(res);
                    done();
                }).catch(err=>{
                    console.log(err);
                    done();
                })
            }

            // 修改插件
            if(this.operate == "edit"){
                kongPluginUpdate(this.pluginEntity).then(res =>{
                    this.msgSuccess("插件修改成功");
                    this.handleCallback();
                    done();
                })

            }

        },

        handleCallback(){
            this.$emit("callback",this.pluginEntity);
        }
    }
    
}
</script>
<style scoped>

</style>